#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_nettle_nettle_func_006.py
@Time:      2024/04/08 14:51:50
@Author:    zhixin
@Version:   1.0
@Contact:   zx01468051@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    zhixin
"""

from common.basetest import LocalTest
import re

class Test(LocalTest):
    """
    See tc_nettle_nettle_func_006.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """
    PARAM_DIC = {"pkg_name": "nettle nettle-devel gcc valgrind"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = """cat > nettle_test6.c <<EOF
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <nettle/hmac.h>

int main() {
    // 待处理的消息
    const char *message = "Hello, Nettle HMAC!";
    const size_t message_len = strlen(message);
    // 密钥
    const uint8_t key[] = "secret key";
    
    // HMAC结果
    uint8_t digest[SHA256_DIGEST_SIZE]; // 对于HMAC-SHA256，结果大小与SHA-256相同
    struct hmac_sha256_ctx hmac_ctx;

    // 运行次数
    const int iterations = 10000;

    printf("开始连续加密测试...\\n");

    for (int i = 0; i < iterations; ++i) {
        // 初始化HMAC-SHA256上下文
        hmac_sha256_set_key(&hmac_ctx, sizeof(key) - 1, key);
        // 计算HMAC-SHA256
        hmac_sha256_update(&hmac_ctx, message_len, (uint8_t *)message);
        hmac_sha256_digest(&hmac_ctx, SHA256_DIGEST_SIZE, digest);
        
    }

    printf("连续加密测试完成。\\n");

    return 0;
}
EOF"""

        self.cmd(cmdline)
    
    def test(self):
        self.cmd('gcc -o nettle_test6 nettle_test6.c -lnettle')
        self.cmd("valgrind --leak-check=full ./nettle_test6 > nettle.log 2>&1")
        code, nettle_result = self.cmd("cat nettle.log", ignore_status=True)
        self.assertIn("All heap blocks were freed -- no leaks are possible", nettle_result)


    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd('rm -rf nettle_test6 nettle_test6.c nettle.log')
